#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <string.h>

#define MAX_SIZE 16384

unsigned int *head;
unsigned int *tail;

typedef struct thread_parms {
	int cfd;
} thread_parms;

void *db_base;

int main(int argc,char **argv)
{
	return 0;
}


void *db_access(void *arg)
{

}



unsigned int server_socket(int port)
{
	int fd=socket(PF_INET,SOCK_STREAM,0);
	if(fd == -1)
	{
		perror("server_socket:socket:");
		return 0;
	}
	struct sockaddr_in addr;
	memset(&addr,0,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_addr.s_addr=htonl(INADDR_ANY);
	addr.sin_port=htons(port);
	int ret=bind(fd,(struct sockaddr *)&addr,sizeof(addr));
	if(ret == -1)
	{
		perror("server_socket:bind:");
		return 0;
	}
	return fd;
}

unsigned int db_read(void **data,unsigned int *size)
{
	if( *head == *tail)
		return 0;

	*size=*((unsigned int *)(db_base+ *tail));
	*tail += sizeof(unsigned int);
	data=db_base+ *tail;
	*tail += *size;
	return 1;
}

unsigned int db_write(void *data,int size)
{
	if( *head + size >= *tail)
		return 0;

	memcpy(db_base+ *head,&size,sizeof(size));
	*head += sizeof(unsigned int);
	memcpy(db_base+ *head,data,size);
	*head += size ;
	return 1;
}

unsigned int db_size(int fd)
{
	struct stat st;
	memset(&st,0,sizeof(st));	
	int ret=fstat(fd,&st);
	if(ret = -1)
	{
		perror("db_size:fstat:");
		return 0;
	}
	return st.st_size;
}

unsigned int db_init(unsigned int size,int new)
{
	if(new == 1)
	{
		memset(db_base,0,size);
	}
	head=(unsigned int *)db_base;
	tail=((unsigned int *)db_base) + 1;
	if(new == 1)
	{
		*head=2*sizeof(unsigned int);
		*tail=2*sizeof(unsigned int);
	}
	return 1;
}

unsigned int db_map(int fd,unsigned int size)
{
	db_base=mmap(NULL,size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	if(db_base == MAP_FAILED)
	{
		perror("db_map:mmap:");
		return 0;
	}
	close(fd);
	return 1;
}
unsigned int db_unmap(unsigned int length)
{
	return munmap(db_base,length);
}

unsigned int db_open(const char *db)
{
	int flags=O_RDWR;
	int fd=open(db,flags);
	if(fd == -1)
	{
		perror("db_open:open:");
		return 0;
	}
	return fd;
}

unsigned int db_create(const char *db,unsigned int size)
{
	int flags=O_RDWR|O_CREAT|O_TRUNC;
	int fd=open(db,flags);
	if(fd == -1)
	{
		perror("db_create:open:");
		return 0;
	}
	int ret=ftruncate(fd,size);
	if(ret == -1)
	{
		perror("db_create:ftruncate:");
		return 0;
	}
	return fd;
}
